import copy
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from Notes.models import Note
from SecureHelperServer.settings import formatResponseData
from utils.conf import verifyID, Response
from utils.custom import MyJWTAuthentication


class GetNote(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        获取Note
        """
        data = copy.deepcopy(formatResponseData)
        try:
            noteId = request.data.get("id")

            if not noteId:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            if not verifyID(noteId):
                return Response(data=data, responseMsg="记录不存在",
                                loggerMsg=f"获取Note：noteId={noteId}不是一个有效的id", isError=True)

            note = Note.objects.filter(id=noteId, user=request.user).first()

            if not note:
                return Response(data=data, responseMsg="记录不存在",
                                loggerMsg=f"获取Note：未找到noteId={noteId}对应的note", isError=True)

            noteObj = {
                "id": note.id,
                "content": note.content,
                "timeStamp": note.timeStamp,
            }

            data["data"]["note"] = noteObj
            return Response(data=data, loggerMsg=f"获取Note: 成功，noteId={noteId}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
